<?php

namespace app\index\controller;

use app\index\model\Member as MemberModel;
use app\index\service\Member as MemberService;
use think\cache\driver\Redis as RedisModel;
use think\captcha\Captcha;

class Member extends Basic
{

    protected $member_id;

    protected function initialize()
    {
        parent::initialize();
    }

    public function __construct()
    {
        parent::__construct();
        $this->member_id = session('member_id');
    }

    /**
     * 导航
     * @return type
     */
    public function navigator()
    {
        if ($this->request->isPost() && input('change_info', ''))
        {

             return MemberService::change_info($this->member_id);
        }
        if ($this->request->isPost() && input('change_password', ''))
        {
            return MemberService::change_password($this->member_id);
        }
        $member_info = MemberService::getInfoByID($this->member_id);
        $title = '个人';
        $this->assign(compact([
            'member_info',
             'title',
        ]));
        return $this->fetch('navigator');
    }



    public function index()
    {
        return '<style type="text/css">*{ padding: 0; margin: 0; } div{ padding: 4px 48px;} a{color:#2E5CD5;cursor: pointer;text-decoration: none} a:hover{text-decoration:underline; } body{ background: #fff; font-family: "Century Gothic","Microsoft yahei"; color: #333;font-size:18px;} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.6em; font-size: 42px }</style><div style="padding: 24px 48px;"> <h1>:) </h1><p> ThinkPHP V5.1<br/><span style="font-size:30px">12载初心不改（2006-2018） - 你值得信赖的PHP框架</span></p></div>'
                . '<script type="text/javascript" src="https://tajs.qq.com/stats?sId=64890268" charset="UTF-8"></script><script type="text/javascript" src="https://e.topthink.com/Public/static/client.js"></script><think id="eab4b9f840753f8e7"></think>';
    }

    public function info($name = 'ThinkPHP5')
    {
        echo phpinfo();
        exit;
    }

    public function login()
    {
        session('member_id', null);
        if ($this->request->isPost())
        {
            return $this->login_verify();
        }
        $title = "登陆";
        $this->assign(compact([
            'title',
        ]));
        $this->assign([
            'hide_nav' => 1,
        ]);
        return $this->fetch();
    }

    public function register()
    {
        if ($this->request->isPost())
        {
            return $this->register_verify();
        }
        $title = "注册";
        $this->assign(compact([
            'title',
        ]));
        $this->assign([
            'hide_nav' => 1,
        ]);
        return $this->fetch();
    }

    public function register_verify()
    {
        $data = input('post.');
        $title = "验证";
//        dump($_POST);
        $validate_rule = [
//            'captcha' => 'require|captcha',
            'phone' => 'require|unique:member|mobile',
            'password' => 'require|min:6',
        ];
        $validate_msg = [
            'captcha' => '验证码不正确',
            'phone.mobile' => '手机号格式不正确',
            'phone.unique' => '同一手机号不能重复注册',
            'phone.require' => '手机号必填',
            'password.min' => '密码最少六位',
            'password.require' => '密码必填',
        ];
        $validate_res = $this->validate($data, $validate_rule, $validate_msg);
        if ($validate_res === true)
        {
            if (!empty($this->get_register_limit()))
            {
                return json([ 'code' => 0, 'msg' => '同一IP,30分钟内只能注册一个账号' ]);
            }
            $res = MemberModel::create([
                        'phone' => $data['phone'],
                        'password' => encrypt_password($data['password']),
            ]);
            $res = db('member')->find();
            if (!$res)
            {
                return json([ 'code' => 0, 'msg' => '注册失败' ]);
            }
            $this->set_register_limit();
            return json([ 'code' => 1, 'msg' => '注册成功' ]);
        }
        else
        {
            return json([ 'code' => 0, 'msg' => $validate_res ]);
        }
//        halt($validate_res);
        $this->assign(compact([
            'title',
        ]));
        return "验证失败";
    }

    private function login_verify()
    {
        $data = input('post.');
        $title = "验证";
//        验证
        $validate_rule = [
//            'captcha' => 'require|captcha',
            'phone' => 'require|mobile',
            'password' => 'require|min:6',
        ];
        $validate_msg = [
            'captcha' => '验证码不正确',
            'phone' => '手机号不正确',
            'password' => '密码不正确',
        ];
        $login_error = 0;
        $return_msg = '';
        $code = 0;
        $ret_captcha = 0;
        $res = MemberModel::where([ 'phone' => $data['phone'], ])->find();
        if (!empty($res))
        {
            $login_error = $this->get_login_times($res->id);
        }
        if ($login_error >= 3)
        {
            $ret_captcha = 1;
            if ($login_error > 3)
            {
                $validate_rule['captcha'] = 'require|captcha';
            }
        }

        $validate_res = $this->validate($data, $validate_rule, $validate_msg);
        switch (true)
        {
            case(is_string($validate_res)):
                $return_msg = $validate_res;
                break;
            case(empty($res)):
                $return_msg = '账号未注册';
                break;
            case(password_verify($data['password'], $res['password']) == false):
                $return_msg = '密码错误';
                $this->inc_login_times($res->id);
                break;
            default:
                $code = 1;
                $return_msg = '登陆成功';
                session('member_id', $res->id);
                session('member_info', $res->toArray());
                break;
        }
        return json([ 'code' => $code, 'msg' => $return_msg, 'captcha' => $ret_captcha, 'login_error' => $login_error ]);
    }

    private function inc_login_times($member_id)
    {
        $key = 'member_' . $member_id . '_login_error';
        $redis_model = new RedisModel([
            'expire' => 60 * 15,
        ]);
        $login_error = $redis_model->get($key);
        if (!empty($login_error))
        {
            $login_error++;
        }
        else
        {
            $login_error = 1;
        }
        $redis_model->set($key, $login_error);
    }

    /**
     * 登陆失败次数
     * @param type $member_id
     * @return type
     */
    private function get_login_times($member_id)
    {
        $key = 'member_' . $member_id . '_login_error';
        $redis_model = new RedisModel([
            'expire' => 60 * 15,
        ]);
        $login_error = $redis_model->get($key);
        return $login_error;
    }

    private function set_register_limit()
    {
        $key = 'ip_' . $this->request->server('remote_addr') . '_register_limit';
        $redis_model = new RedisModel([
            'expire' => 60 * 30,
        ]);
        $redis_model->set($key, 1);
    }

    private function get_register_limit()
    {
        $key = 'ip_' . $this->request->server('remote_addr') . '_register_limit';
        $redis_model = new RedisModel([
            'expire' => 60 * 30,
        ]);
        $register_limit = $redis_model->get($key);
        return $register_limit;
    }

    public function captcha()
    {
        $config = [
            'length' => 4,
        ];
        $captcha = new Captcha($config);
        return $captcha->entry();
    }

}
